﻿/*******************************************************************************
 * 
 * 
 * 文件名：FrmMain.cs
 * 
 * 日  期：2009-05-04
 * 
 * 版  本：1.0.0
 * 
 * Copyright (C) 2009 Gsino
 * 
 * 功  能：主窗体
 *          1. 菜单栏功能调用
 *          2. 工具栏功能调用
 *          3. 状态栏功能设置
 *          4. 串口数据的解析与操作
 *          5. 监控面板编辑的相关操作
 *          6. 托盘功能
 *          7. F1功能键
 * 
 * 修改记录
 * 
 * 版本         修改日期            修改人          修改内容
 * 1.0.0        2009-05-04          段洪锦          1. 监控面板编辑的退出编辑中坐标查询提出到底层
 *                                                  2. 自动添加显示仪出的数据库操作规范
 *                                                  3. 监控数据插入到数据表操作规范
 *                                                  5. 添加声音报警
 *                                                  6. 数据存储周期设置
 *                                                  7. 代码的整理与注释
 * 
 * 1.0.1        2009-05-07          段洪锦          1. 将监控时数据库的持续连接方法改为解析一个数据包就重新打开一次数据库
 *                                                  2. 在对串口数据进行过滤前判读温湿度数据是否为合法的浮点数
 *                                                  3. 添加串口定时重启的功能
 * 
 * 1.0.2        2009-05-21          段洪锦          1. 修改监控时打开关闭数据，将其改为，每x个数据包关闭一次
 *                                                  2. 项目-》属性-》应用程序-》程序集信息 修改公司名为InTemHumSys
 * 1.0.3        2009-08-11          段洪锦          1. 修改上传数据的解析方式，温湿度数据由字符串该成了原始数据，在数据解析前有解析协议
 *                                                  2. 修改解析数据后更新显示面板和更新数据库
 * 
 * 
 *******************************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BLL.Spublic;
using Entity;
using BLL.TableFunc;
using System.IO;
using 电力热故障系统.Properties;
using System.Threading;
using System.Collections;
using System.Data.OleDb;
using System.Text.RegularExpressions;

namespace 电力热故障系统
{
    public partial class Form1 : Form
    {
        #region 本类全局变量

        Mutex mMutex;

        /// <summary>
        /// 最高温度（用于过滤数据）
        /// </summary>
        private const float _Htem = 120.0f;

        /// <summary>
        /// 最低温度（用于过滤数据）
        /// </summary>
        private const float _Ltem = -20.0f;

        /// <summary>
        /// 最高湿度（用于过滤数据）
        /// </summary>
        private const float _Hhum = 100.0f;

        /// <summary>
        /// 最低湿度（用于过滤数据）
        /// </summary>
        private const float _Lhum = 0.0f;

        /// <summary>
        /// 设置串口时是否点击了退出操作
        /// </summary>
        public static bool isSerCancle = false;
        /// <summary>
        /// Self_Variable:起始路径
        /// </summary>
        string path = string.Empty;

        /// <summary>
        /// 监视面板数组
        /// </summary>
        public static List<ControlBoard> MainTempBoards;

        /// <summary>
        /// 是否已经建立了连接
        /// </summary>
        public static bool isBuildConnect = false;

        /// <summary>
        /// 报警标识符
        /// </summary>
        private bool tmpAlarm = false;
        private bool hmdAlarm = false;

        /// <summary>
        /// Self_Variable:非数据库公有方法
        /// </summary>
        OtherFunc otherfuc = new OtherFunc();

        /// <summary>
        /// Self_Varibale: 串口类
        /// </summary>
        static public ComPort datacomport;

        /// <summary>
        /// 是否设置了阀值
        /// </summary>
        static public bool isSetPanelset = false;

        /// <summary>
        /// Self_Variable: 线程
        /// </summary>
        private Thread _ComDataThread;

        /// <summary>
        /// 定义委托，添加新的监视面板
        /// </summary>
        /// <param name="newBoard"></param>
        private delegate void AddCtrlBoardHandler(ControlBoard newBoard);

        private AddCtrlBoardHandler addBoard;

        /// <summary>
        /// Self_Variable: 用户权限
        /// </summary>
        public static string userpower = Program.obj.Userpower;

        /// <summary>
        /// 新建节点集
        /// </summary>
        private Panelnode[] _tempnode;

        /// <summary>
        /// 状态栏第一项的名称
        /// </summary>
        public static string statusFirstName = "准备就绪";

        private const string isWatching = "正在监控";

        private const string isReady = "准备就绪";

        /// <summary>
        /// 用户保存连接状态的初始图片；
        /// </summary>
        private Image tsslSerImage;

        /// <summary>
        /// 保存温度状态的图片
        /// </summary>
        private Image tsslTempImage;

        private DatabaseFunc db = new DatabaseFunc();

        private OtherFunc of = new OtherFunc();

        private  OtherFunc span = new OtherFunc();

        private DataTbUpdate _datatbUpdate = null;

        /// <summary>
        /// 用于存储上次插入数据库的时间，其排序和MainTempBoard一样
        /// </summary>
        private ArrayList lastTime = new ArrayList();

        /// <summary>
        /// 最近一次重启串口的时间
        /// </summary>
        private int SerialOTime;

        /// <summary>
        /// 重启串口的时间间隔（小时）
        /// </summary>
        private int SerialReOPEN = 1;

        /// <summary>
        /// 执行dbIOTimes个数据包解析，重启数据库
        /// </summary>
        private int dbIOTimes = 100;

        private string helpname = "工业温湿度监测系统帮助.CHM";

        /// <summary>
        /// 单条命令的长度
        /// </summary>
        private const int DATA_LENGTH = 10;

        #endregion

        #region 默认构造方法

        public Form1()
        {
            InitializeComponent();

            this.toolStrip2.Height = 0;
            this.ButtonMapMange.Height = 0;
            this.ButtonSave.Height = 0;
            this.ButtonAuto.Height = 0;
            this.ButtonCancle.Height = 0;
            this.ButtonQuit.Height = 0;
            this.label3.Visible = false;
            this.label4.Visible = false;

            this.label2.Height = 0;
            //this.toolStrip2.Visible = false;

            addBoard = new AddCtrlBoardHandler(AddCtrlBoard);
            this.ConLabel.Visible = false;
            this.AlarmLabel.Visible = false;
            tsslSerImage = this.tsslSerStatus.Image;
            tsslTempImage = this.tsslPanStatus.Image;

            this.ButtonAuto.BringToFront();
            this.ButtonCancle.BringToFront();
            this.ButtonMapMange.BringToFront();
            this.ButtonQuit.BringToFront();
            this.ButtonSave.BringToFront();

            SerialOTime = of.GetUnixNow();
        }

        #endregion

        #region 窗体加载

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            bool bCreateNew;
            mMutex = new Mutex(false, "DYYGsinoTem20080410", out bCreateNew);

            #region 查询该用户对各模块的权限

            if (userpower != "")
            {
                string[] _userp = userpower.Split(',');
                int _length = _userp.Length;
                for (int _index = 0; _index < _length; _index++)
                {
                    switch ((UserPower)Convert.ToInt16(_userp[_index]))
                    {
                        case UserPower.RealtimeWatch:                      // 实时监控
                            toolStripButton2.Enabled = true;                //工具
                            建立连接ToolStripMenuItem1.Enabled = true;      //菜单
                            break;
                        case UserPower.DataCheck:                           //数据查询
                            数据查询ToolStripMenuItem1.Enabled = true;      //菜单（数据查询：包括温度，报警，日志查询）
                            toolStripButton4.Enabled = true;                //温度查询（工具栏）
                            toolStripButton5.Enabled = true;                //报警查询（工具栏）
                            break;
                        case UserPower.SystemSet:                           //系统设置
                            串口设置ToolStripMenuItem1.Enabled = true;
                            监控区域管理ToolStripMenuItem1.Enabled = true;
                            监控面板编辑ToolStripMenuItem1.Enabled = true;
                            toolStripButton1.Enabled = true;                //串口设置（工具栏）
                            toolStripButton6.Enabled = true;                //设备管理（工具栏）
                            break;
                        case UserPower.DataBaseManage:                      //数据管理
                            数据管理ToolStripMenuItem1.Enabled = true;      //数据管理
                            break;
                        default:
                            break;
                    }
                }
            }
            #endregion

            this.LogInUser.Text = "当前用户:" + Program.obj.Username;

            path = Directory.GetCurrentDirectory();

            if (Directory.Exists(path + "\\img"))
            {
                if (Settings.Default.imagePath != "")
                {
                    this.picBackground.Image = Image.FromFile(Settings.Default.imagePath);
                }
            }
            if (Settings.Default.startlink != null)
            {
                if (Settings.Default.startlink == "1" && toolStripButton2.Enabled == true)
                {
                    建立连接ToolStripMenuItem1_Click(sender, e);
                }
            }
            this.label2.Focus();
            this.panel1.AutoScroll = true;
        }

        #endregion 

        #region 工具栏（串口设置，建立连接，断开连接，温湿度查询，报警查询，监控区域管理）

                #region 串口设置

                /// <summary>
                /// 串口设置
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void toolStripButton1_Click(object sender, EventArgs e)
                {
                    串口设置ToolStripMenuItem1_Click(sender, e);
                }

                #endregion

                #region 建立连接

                /// <summary>
                /// 建立连接
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void toolStripButton2_Click(object sender, EventArgs e)
                {
                    建立连接ToolStripMenuItem1_Click(sender, e);
                }

                #endregion

                #region 断开连接

                /// <summary>
                /// 断开连接
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void toolStripButton3_Click(object sender, EventArgs e)
                {
                    断开连接ToolStripMenuItem1_Click(sender, e);
                }

                #endregion

                #region 温湿度查询
                
                /// <summary>
                /// 温湿度查询
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void toolStripButton4_Click(object sender, EventArgs e)
                {
                    温湿度查询ToolStripMenuItem1_Click(sender, e);
                }

                #endregion

                #region 报警查询

                /// <summary>
                /// 报警查询
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void toolStripButton5_Click(object sender, EventArgs e)
                {
                    报警查询ToolStripMenuItem1_Click(sender, e);
                }

                #endregion

                #region 监控区域管理

                /// <summary>
                /// 设备管理
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void toolStripButton6_Click(object sender, EventArgs e)
                {
                    监控区域管理ToolStripMenuItem1_Click(sender, e);
                }

                #endregion

        #endregion

        #region 菜单栏

            #region 系统管理（用户管理，数据管理，建立连接，断开连接，系统退出）

                #region 用户管理

                /// <summary>
                /// 用户管理
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void toolStripMenuItem4_Click(object sender, EventArgs e)
                {
                    FrmUserManage _frmUserManage = new FrmUserManage();
                    statusFirstName = "用户管理"; //任务栏第一项
                    _frmUserManage.ShowDialog();
                    statusFirstChange();//关闭用户管理后，重新设置状态栏的第一项
                }

                #endregion

                #region 数据管理

                /// <summary>
                /// 数据管理
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 数据管理ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    if (isBuildConnect == true)
                    {
                        MessageBox.Show("请先断开连接，再进行数据管理操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    FrmBackup _frmBackup = new FrmBackup();
                    statusFirstName = "数据管理"; //设置状态栏的第一项
                    _frmBackup.ShowDialog();
                    statusFirstChange(); //管理窗口后，重新设置状态栏的第一项
                }

                #endregion

                #region 建立连接

                /// <summary>
                /// 建立连接
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 建立连接ToolStripMenuItem1_Click(object sender, EventArgs e)
                {

                    using (LogTablesFunc log = new LogTablesFunc())
                    {
                        //判断是否存在默认的串口和默认的波特率
                        if (Settings.Default.serialPortName == string.Empty || Settings.Default.serialBaudrate == string.Empty)
                        {
                            //判断当前用户是否拥有串口设置的权限
                            if (userpower.IndexOf('3') > -1)
                            {
                                //设置串口和波特率
                                SerialCom serialport = new SerialCom();
                                serialport.noCom = true;
                                serialport.ShowDialog();
                                if (isSerCancle == true)
                                    return;
                            }
                            else
                            {
                                MessageBox.Show("串口未设置，请联系管理员进行设置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return;
                            }

                        }
                        //打开串口
                        datacomport = new ComPort();
                        datacomport.PortName = Settings.Default.serialPortName;
                        datacomport.Baudrate = Settings.Default.serialBaudrate;
                        datacomport.OpenPort();

                        if (!isBuildConnect)// 判断串口是否已打开
                            return;

                        BoardsInit();//初始化显示仪面板

                        if (MainTempBoards.Count <= 0)
                        {
                            MessageBox.Show("当前数据库中不存在区域", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        _datatbUpdate = new DataTbUpdate(); //打开数据库

                        //新开线程用于处理串口数据
                        _ComDataThread = new Thread(DataAnalyseTh);
                        _ComDataThread.IsBackground = true;
                        _ComDataThread.Start();

                        this.tsslSerStatus.Text = "连接正常";
                        this.tsslSerStatus.Image = this.ConLabel.Image;

                        this.toolStripButton3.Enabled = true;
                        this.断开连接ToolStripMenuItem1.Enabled = true;
                        this.toolStripButton2.Enabled = false;
                        this.建立连接ToolStripMenuItem1.Enabled = false;

                        //写入日志
                        int datetimeunixnow = otherfuc.GetUnixNow();
                        log.insertLog(datetimeunixnow, Program.obj.Username, 2);

                        this.panel1.Focus();
                        statusFirstName = isWatching;
                    }

                }

                #endregion

                #region 断开连接

                /// <summary>
                /// 断开连接
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 断开连接ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    using (LogTablesFunc log = new LogTablesFunc())
                    {
                        isBuildConnect = false;
                        //写入日志
                        int datetimeunixnow = otherfuc.GetUnixNow();
                        log.insertLog(datetimeunixnow, Program.obj.Username, 4);
                        //关闭串口
                        datacomport.ClosePort();
                        Thread.Sleep(10);

                        _ComDataThread.Abort();//终止传里串口数据的线程

                        _datatbUpdate.CloseDataBase();//关闭数据库

                        BoardsDispose();//释放显示仪面板，清空显示区域

                        this.toolStripButton3.Enabled = false;
                        this.断开连接ToolStripMenuItem1.Enabled = false;
                        this.toolStripButton2.Enabled = true;
                        this.建立连接ToolStripMenuItem1.Enabled = true;
                        statusFirstName = isReady;
                        this.tsslSerStatus.Text = "连接已断开";
                        this.tsslSerStatus.Image = tsslSerImage;


                        SerialOTime = of.GetUnixNow();

                    }

                }

                #endregion        

                #region 系统退出

                /// <summary>
                /// 系统退出
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 系统退出ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    using (LogTablesFunc log = new LogTablesFunc())
                    {
                        DialogResult result = MessageBox.Show("确认要退出系统吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                        if (result == DialogResult.OK)
                        {
                            this.notifyIcon1.Dispose();//释放托盘
                            //当前格林威治时间
                            int datetimeunixnow = otherfuc.GetUnixNow();
                            log.insertLog(datetimeunixnow, Program.obj.Username, 3);
                            Application.ExitThread();
                        }
                        else if (result == DialogResult.Cancel)
                            return;
                    }
                }

                #endregion

            #endregion

            #region 数据查询（温湿度查询，报警查询，日志查询）

                #region 温湿度查询

                /// <summary>
                /// 温湿度查询
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 温湿度查询ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    FormTemp _formTemp = new FormTemp();
                    statusFirstName = "温湿度查询";
                    _formTemp.ShowDialog();
                    statusFirstChange();
                }

                #endregion

                #region 报警查询

                /// <summary>
                /// 报警查询
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 报警查询ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    FormAlarm _formAlarm = new FormAlarm();
                    statusFirstName = "报警查询";
                    _formAlarm.ShowDialog();
                    statusFirstChange();
                }

                #endregion

                #region 日志查询

                /// <summary>
                /// 日志查询
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 日志查询ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    FormLog _formLog = new FormLog();
                    statusFirstName = "日志查询";
                    _formLog.ShowDialog();
                    statusFirstChange();
                }

                #endregion

            #endregion
                                                                                                   
            #region  系统设置（串口设置，监控区域管理，监控面板编辑，系统参数设置）

                #region 串口设置

                /// <summary>
                /// 串口设置
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 串口设置ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    if (isBuildConnect == true)
                    {
                        MessageBox.Show("请先断开连接，再进行串口设置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    SerialCom serialport = new SerialCom();

                    statusFirstName = "串口设置";

                    serialport.ShowDialog();
                    statusFirstChange();
                }

                #endregion

                #region 监控区域管理

                /// <summary>
                /// 监控区域管理
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 监控区域管理ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    if (isBuildConnect == true)
                    {
                        MessageBox.Show("请先断开连接再进行监控区域的设置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    FrmDevice _frmDevice = new FrmDevice();
                    statusFirstName = "监控区域管理";
                    _frmDevice.ShowDialog();
                    statusFirstChange();
                }

                #endregion

                #region 监控面板编辑

                /// <summary>
                /// 监控面板编辑
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 监控面板编辑ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    //快捷栏展开 
                    spread();

                    if (MainTempBoards != null)
                    {
                        //将各个显示面板置为可移动状态
                        for (int i = 0; i < MainTempBoards.Count; i++)
                        {
                            MainTempBoards[i].ControlBoard_AllowDrag(true);
                        }
                    }

                    this.panel1.Focus();
                }

                #endregion

                #region 系统参数设置

                /// <summary>
                /// 系统参数设置
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 系统参数设置ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    FrmStartOption option = new FrmStartOption();
                    statusFirstName = "系统参数设置";
                    option.ShowDialog();
                    statusFirstChange();
                }

                #endregion

           #endregion

            #region 系统帮助（关于，系统帮助）

                #region 关于
            
                /// <summary>
                /// 关于
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 关于ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    FrmAbout f = new FrmAbout();
                    statusFirstName = "关于系统";
                    f.ShowDialog();
                    statusFirstChange();
                }

                #endregion

                #region 系统帮助

                /// <summary>
                /// 系统帮助
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void 帮助ToolStripMenuItem1_Click(object sender, EventArgs e)
                {
                    if (File.Exists(Dirpath.Syspath + helpname))
                    {
                        System.Diagnostics.Process p = new System.Diagnostics.Process();
                        p.StartInfo.FileName = Dirpath.Syspath + helpname;
                        p.Start();
                    }
                    else
                    {
                        MessageBox.Show("未找到帮助文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }

                #endregion

            #endregion

        #endregion

        #region 状态栏

                #region 定时器，刷新状态栏的时间

                /// <summary>
                /// 定时器，刷新状态栏的时间
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void StatusTimer_Tick(object sender, EventArgs e)
                {
                    //更新状态栏信息
                    this.tsslReady.Text = statusFirstName;
                    tsslTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    bool _istAlarm = false;
                    bool _ishAlarm = false;
                    bool _isAlarm = false;
                    if (isBuildConnect == true)
                    {
                        //查找报警
                        for (int i = 0; i < MainTempBoards.Count; i++)
                        {
                            if (MainTempBoards[i].IsTmpAlarmFlag == true)
                            {
                                _istAlarm = true;
                                break;
                            }
                        }
                        for (int i = 0; i < MainTempBoards.Count; i++)
                        {
                            if (MainTempBoards[i].IsHmdAlarmFlag == true)
                            {
                                _ishAlarm = true;
                                break;
                            }
                        }
                        for (int i = 0; i < MainTempBoards.Count; i++)
                        {
                            if (MainTempBoards[i].IsAlarmFlag == true)
                            {
                                _isAlarm = true;
                                break;
                            }
                        }
                        if (_isAlarm)
                        {
                            tsslPanStatus.Text = "温湿度异常";
                            this.tsslPanStatus.Image = this.AlarmLabel.Image;
                        }
                        else
                        {
                            if (_istAlarm)
                            {
                                if (!_ishAlarm)
                                {
                                    tsslPanStatus.Text = "温度异常";
                                    this.tsslPanStatus.Image = this.AlarmLabel.Image;
                                }
                                else
                                {
                                    tsslPanStatus.Text = "温湿度异常";
                                    this.tsslPanStatus.Image = this.AlarmLabel.Image;
                                }
                            }
                            else
                            {
                                if (_ishAlarm)
                                {
                                    tsslPanStatus.Text = "湿度异常";
                                    this.tsslPanStatus.Image = this.AlarmLabel.Image;
                                }
                                else
                                {
                                    tsslPanStatus.Text = "温湿度正常";
                                    this.tsslPanStatus.Image = tsslTempImage;
                                }
                            }
                        }
                        string isAlarmseted = Settings.Default.isAlarmSeted;

                        //蜂鸣器报警
                        if ((_isAlarm || _ishAlarm || _istAlarm) && isAlarmseted != "0")
                            Console.Beep();
                    }
                    else
                    {
                        tsslPanStatus.Text = "温湿度正常";
                        this.tsslPanStatus.Image = tsslTempImage;
                    }

                    if (isBuildConnect == true)
                    {
                        int now = of.GetUnixNow();
                        if (now - SerialOTime > SerialReOPEN * 3600)
                        {
                            if (datacomport.isOpen == true)
                            {
                                datacomport.ClosePort();
                                datacomport.OpenPort();
                            }
                            SerialOTime = now;
                        }
                    }

                    //this.panel1.Focus();
                }

                #endregion 

                #region 状态栏报警时的事件

                /// <summary>
                /// 状态栏报警时的事件
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void tsslPanStatus_Click(object sender, EventArgs e)
                {
                    bool _istAlarm = false;
                    bool _ishAlarm = false;
                    bool _isAlarm = false;
                    ArrayList paddr = new ArrayList();
                    if (isBuildConnect == true)
                    {
                        for (int i = 0; i < MainTempBoards.Count; i++)
                        {
                            if (MainTempBoards[i].IsAlarmFlag == true)
                            {
                                _isAlarm = true;
                                if (paddr.Contains(MainTempBoards[i]) == false)
                                    paddr.Add(MainTempBoards[i].paneladdr);
                            }
                            if (MainTempBoards[i].IsHmdAlarmFlag == true)
                            {
                                _ishAlarm = true;
                                if (paddr.Contains(MainTempBoards[i]) == false)
                                    paddr.Add(MainTempBoards[i].paneladdr);
                            }
                            if (MainTempBoards[i].IsTmpAlarmFlag == true)
                            {
                                _istAlarm = true;
                                if (paddr.Contains(MainTempBoards[i]) == false)
                                    paddr.Add(MainTempBoards[i].paneladdr);
                            }
                        }
                    }
                    if (_isAlarm == true || _istAlarm == true || _ishAlarm == true)
                    {
                        int _starttime = otherfuc.GetUnixStartTime();
                        int _endtime = otherfuc.GetUnixEndTime();
                        FormAlarm f = new FormAlarm();
                        f.StartTime = _starttime;
                        f.EndTime = _endtime;
                        f.TreeList = paddr;
                        f.Query();
                        statusFirstName = "报警查询";
                        f.ShowDialog();
                        statusFirstChange();
                    }
                }

                #endregion 

                #region 状态栏第一项的名称

                /// <summary>
                /// 状态栏第一项的名称
                /// </summary>
                private void statusFirstChange()
                {
                    if (isBuildConnect)
                        statusFirstName = isWatching;
                    else
                        statusFirstName = isReady;
                }

                #endregion


        #endregion

        #region 启动

        /// <summary>
        /// 启动(初始化显示面板)
        /// </summary>
        private void BoardsInit()
        {
            MainTempBoards = new List<ControlBoard>();

            using (PanelTablesFunc paneldata = new PanelTablesFunc())
            {
                DataSet pds = paneldata.selcPanel();
                for (int pi = 0; pi < pds.Tables[0].Rows.Count; pi++)
                {
                    ControlBoard onetempboard = new ControlBoard();

                    onetempboard.panelName = pds.Tables[0].Rows[pi].ItemArray[0].ToString();
                    onetempboard.Location = new Point(Convert.ToInt32(pds.Tables[0].Rows[pi].ItemArray[2]) + this.label2.Location.X,
                                                      Convert.ToInt32(pds.Tables[0].Rows[pi].ItemArray[3]) + this.label2.Location.Y);
                    onetempboard.maxTemp = Convert.ToInt32(pds.Tables[0].Rows[pi].ItemArray[4]);
                    onetempboard.paneladdr = Convert.ToInt16(pds.Tables[0].Rows[pi].ItemArray[1]);
                    onetempboard.panelid = Convert.ToInt32(pds.Tables[0].Rows[pi].ItemArray[5]);
                    onetempboard.i_htemp = Convert.ToInt32(pds.Tables[0].Rows[pi].ItemArray[4]);
                    onetempboard.i_hihum = Convert.ToInt32(pds.Tables[0].Rows[pi].ItemArray[7]);
                    onetempboard.i_ltemp = Convert.ToInt32(pds.Tables[0].Rows[pi].ItemArray[6]);
                    onetempboard.i_lohum = Convert.ToInt32(pds.Tables[0].Rows[pi].ItemArray[8]);

                    if (this.toolStrip2.Height == 25)
                    {
                        onetempboard.ControlBoard_AllowDrag(true);
                    }
                    this.panel1.Controls.Add(onetempboard);
                    onetempboard.BringToFront();
                    MainTempBoards.Add(onetempboard);
                    //存储插入数据库的时间
                    pLastTime _plt = new pLastTime();
                    _plt._paddr = Convert.ToInt16(pds.Tables[0].Rows[pi].ItemArray[1]);
                    _plt._node = 1;
                    _plt.time = 0;
                    lastTime.Add(_plt);
                }
                _tempnode = new Panelnode[MainTempBoards.Count];
            }

            //置于底层
            this.picBackground.SendToBack();
        }

        #endregion

        #region 释放

        /// <summary>
        /// 释放(释放显示仪，清空显示区域)
        /// </summary>
        private void BoardsDispose()
        {

            for (int pdi = 0; pdi < MainTempBoards.Count; pdi++)
            {
                MainTempBoards[pdi].Visible = false;
                this.panel1.Controls.Remove(MainTempBoards[pdi]);
                MainTempBoards[pdi].Dispose();
            }
            MainTempBoards.Clear();
            MainTempBoards = null;
        }

        #endregion

        #region 串口操作

                #region 串口操作入口函数

                /// <summary>
                /// 串口操作入口函数
                /// </summary>
                public void DataAnalyseTh()
                {
                    string stmp = "";
                    if (isBuildConnect == false)
                        return;
                    int i = 0;
                    while (true)
                    {
                        if (i > dbIOTimes)
                        {
                            _datatbUpdate.CloseDataBase();
                            _datatbUpdate = new DataTbUpdate();
                            i = 0;
                        }
                        i++;
                        datacomport.DataRecv(ref stmp); //接收数据

                        DataDeal(ref stmp);

                        Thread.Sleep(1000);
                        
                    }
                }

                #endregion

                #region 串口命令解析

                /// <summary>
                /// Self_Function: 串口命令解析
                /// </summary>
                /*解析协议如下：*/
                /*
                 * 假设上传的数据如下：
                 * 02 00 07 05 19 A7 04 B6 1C AC
                 * 其中 02 00 07为固定位，05为节点编号，FF FF温度原始数据，04 B6为湿度原始数据，1C为电量，AC为校验位
                 * 电量=1c * 0.1;
                 * 温度= (19 * 256 + a7)*0.01 -((电量-2)*0.1+39.50)；
                 * 湿度1= 04*256 +B6;
                 * 湿度= -4 + 0.0405×湿度1 -2.8×0.000001 × 湿度1 × 湿度1 +（温度-25）×（0.01+0.00008×湿度1）
                 */
                public int DataDeal(ref string dealcomdata)
                {
                    if (dealcomdata != string.Empty && dealcomdata != null)
                    {
                        int deallen = dealcomdata.Length;/*数据长度*/
                        string s_head = "\x02\x00\x07";
                        while (deallen >= DATA_LENGTH)
                        {
                            int dindex = dealcomdata.IndexOf(s_head);
                            if (dindex >= 0 && (deallen - dindex >= DATA_LENGTH)) /*命令头存在，并且命令长度不小于一条命令的长度*/
                            { 
                                int xorvalue = 0;
                                int xori = 0;
                                for (xori = dindex + 1; xori < dindex + DATA_LENGTH - 1; xori++) /*校验*/
                                {
                                    xorvalue ^= dealcomdata[xori];
                                }/* end for int i = 0;...*/
                                if (xorvalue == dealcomdata[xori])
                                {
                                    float f_ele = (float)(Convert.ToInt32(dealcomdata[dindex + 8]) * 0.1);//电量
                                    if (f_ele > 0.0f && f_ele < 1.0f || f_ele > 2.2f)
                                    {
                                        int i_node = Convert.ToInt32(dealcomdata[dindex + 3]);
                                        float temp = (float)(Convert.ToInt32(dealcomdata[dindex + 4]) * 256 + Convert.ToInt32(dealcomdata[dindex + 5]));
                                        float f_temp = (float)(temp * 0.01 - ((f_ele - 2) * 0.1 + 39.5));//温度
                                        temp = (float)(Convert.ToInt32(dealcomdata[dindex + 6]) * 256 + Convert.ToInt32(dealcomdata[dindex + 7]));
                                        float f_hum =(float)( -4 + 0.0405 * temp - 2.8 * 0.000001 * temp * temp + (f_temp - 25) * (0.01 + 0.00008 * temp));
                                        //if (f_temp >= _Ltem && f_temp <= _Htem && f_hum >= _Lhum && f_hum <= _Hhum)
                                        {
                                            f_temp = (float)(Convert.ToDouble(f_temp.ToString("#0.0")));
                                            f_hum = (float)(Convert.ToDouble(f_hum.ToString("#0.0")));
                                            UpdateDB(i_node, f_temp, f_hum);
                                            UpdateControlBoard(i_node, f_temp, f_hum);
                                        }/*end if */


                                    }/*end if f_ele>0.0...*/
                                    if (deallen - dindex > DATA_LENGTH) /*剩余字节数大于一条命令长度*/
                                    {
                                        dealcomdata = dealcomdata.Substring(dindex + DATA_LENGTH);
                                        deallen = dealcomdata.Length;
                                        continue;
                                    }/*end if deallen - dindex > DATA_LENGTH*/
                                    else/*剩余字节数不足一条命令，清空*/
                                    {
                                        dealcomdata = "";
                                        deallen = 0;
                                    }/*end else*/

                                }/*end if xorvalue == dealcomdata[xori]*/
                                else /*校验失败*/
                                {
                                    dealcomdata = dealcomdata.Substring(dindex + 3);
                                }/*end else (if xorvalue == dealcomdata[xori])*/
                            }/* end if dindex >= 0*/
                            else /*命令头不存在*/
                            {
                                dealcomdata = "";
                                deallen = 0;
                                break;
                            }/*end else (if dindex >= 0)*/
                        }/* end while deallen >= ...*/
                    } /* end if dealcomdata != ...*/
                    return 0;
                }

                #endregion

                #region 更新数据库

                /// <summary>
                /// 更新数据库
                /// </summary>
                /// <param name="paneladdr">节点id</param>
                /// <param name="f_temp">温度</param>
                /// <param name="f_hum">湿度</param>
                private void UpdateDB(int paneladdr, float f_temp, float f_hum) //数据解析处理
                {

                    //上下限阀值
                    int maxtmp = 120;
                    int mintmp = -20;
                    int maxhmd = 100;
                    int minhmd = 0;

                    int _index = -1;
                    //查找监控区域
                    for (int i = 0; i < MainTempBoards.Count; i++)
                    {
                        if (MainTempBoards[i].paneladdr == paneladdr)
                        {
                            _index = i;
                            break;
                        }
                    }
                    if (_index == -1) //插入新区域
                    {
                        DataSet ds = new DataSet();
                        using (PanelTablesFunc pf = new PanelTablesFunc())
                        {
                            //将新的大棚插入到gs_panel中
                            pf.insertPanel(paneladdr, maxtmp, mintmp, maxhmd, minhmd);

                            //新添加显示面板
                            ds = pf.selcPanels(paneladdr);
                        }
                       
                        ControlBoard newControlB = new ControlBoard();
                        newControlB.panelName = ds.Tables[0].Rows[0]["panelname"].ToString();
                        newControlB.paneladdr = Convert.ToInt16(paneladdr);
                        newControlB.panelid = Convert.ToInt32(ds.Tables[0].Rows[0]["panelid"]);
                        newControlB.Location = new Point(Convert.ToInt16(ds.Tables[0].Rows[0]["panelx"]),
                                                          Convert.ToInt16(ds.Tables[0].Rows[0]["panely"]));

                        newControlB.i_htemp = Convert.ToInt32(ds.Tables[0].Rows[0].ItemArray[4]);
                        newControlB.i_hihum = Convert.ToInt32(ds.Tables[0].Rows[0].ItemArray[7]);
                        newControlB.i_ltemp = Convert.ToInt32(ds.Tables[0].Rows[0].ItemArray[6]);
                        newControlB.i_lohum = Convert.ToInt32(ds.Tables[0].Rows[0].ItemArray[8]);

                        if (this.toolStrip2.Height == 25)
                            newControlB.ControlBoard_AllowDrag(true);
                        this.Invoke(addBoard, newControlB);

                        pLastTime _plt = new pLastTime();
                        _plt._paddr = Convert.ToInt16(paneladdr);
                        _plt._node = 1;
                        _plt.time = 0;
                        lastTime.Add(_plt);
                    }

                    int _time = of.GetUnixTime(DateTime.Now.ToString());
                    int cycle = 0;
                    if (Settings.Default.dbcycle != "")
                        cycle = Convert.ToInt32(Settings.Default.dbcycle);
                    else
                        cycle = 1;
                    int _NIndex = 0;
                    if (_index > -1)
                    {
                        _NIndex = _index;
                    }
                    else
                    {
                        _NIndex = lastTime.Count - 1;
                    }
                    pLastTime p = (pLastTime)lastTime[_NIndex];

                    if (_time - p.time >= cycle * 60)
                    {
                        p.time = _time;
                        lastTime[_NIndex] = p;
                        
                        _datatbUpdate.InsertDataTable(paneladdr, 1, f_temp, f_hum, _time);//执行数据插入操作（数据解析后进行插入到数据库中）
                    }

                    ////更新报警信息,是否超过阀值，需要自己判断（多种情况，考虑全面）

                    maxtmp = MainTempBoards[_NIndex].i_htemp;
                    mintmp = MainTempBoards[_NIndex].i_ltemp;
                    maxhmd = MainTempBoards[_NIndex].i_hihum;
                    minhmd = MainTempBoards[_NIndex].i_lohum;

                    int alarmtype; //温湿度报警类型
                    int alarmlimit; //报警上下限

                    OtherFunc span = new OtherFunc();

                    AlarmTablesFunc warning = new AlarmTablesFunc();

                    if (span.checkInSpan(f_temp, mintmp, maxtmp)) //确定温度报警
                    {
                        alarmtype = 0;

                        if (f_temp > maxtmp) //上下限报警
                            alarmlimit = 0;
                        else
                            alarmlimit = 1;

                        warning.AddAlarmInfo(alarmtype, alarmlimit, paneladdr, paneladdr, f_temp, _time);
                    }

                    if (span.checkInSpan(f_hum, minhmd, maxhmd)) //确定湿度报警
                    {
                        alarmtype = 1;

                        if (f_hum > maxhmd) //上下限报警
                            alarmlimit = 0;
                        else
                            alarmlimit = 1;

                        warning.AddAlarmInfo(alarmtype, alarmlimit, paneladdr, paneladdr, f_hum, _time);
                    }

                }
                #endregion

                #region 添加新面板

                /// <summary>
                /// 添加新面板
                /// </summary>
                /// <param name="_board"></param>
                private void AddCtrlBoard(ControlBoard _board)
                {
                    this.panel1.Controls.Add(_board);
                    this.panel1.Update();
                    this.picBackground.SendToBack();
                    _board.BringToFront();
                    MainTempBoards.Add(_board);
                    Array.Resize(ref _tempnode, MainTempBoards.Count);
                }

                #endregion

                #region 更新监视面板

                /// <summary>
                /// 更新监视面板
                /// </summary>
                /// <param name="paneladdr">节点</param>
                /// <param name="f_temp">温度</param>
                /// <param name="f_hum">湿度</param>
                private void UpdateControlBoard(int paneladdr,float f_temp, float f_hum)
                {
                    //阀值
                    int maxtmp = 0;
                    int mintmp = 0;
                    int maxhmd = 0;
                    int minhmd = 0;

                    int _index = -1;
                    //查找监控区域
                    for (int i = 0; i < MainTempBoards.Count; i++)
                    {
                        if (MainTempBoards[i].paneladdr == paneladdr)
                        {
                            _index = i;
                            break;
                        }
                    }
                    if (_index > -1)
                    {
                        maxtmp = MainTempBoards[_index].i_htemp;
                        mintmp = MainTempBoards[_index].i_ltemp;
                        maxhmd = MainTempBoards[_index].i_hihum;
                        minhmd = MainTempBoards[_index].i_lohum;
                        //温度
                        _tempnode[_index].node_A._temp = f_temp;

                        //判断是否有报警
                        if (span.checkInSpan(_tempnode[_index].node_A._temp, mintmp, maxtmp)) //确定温度报警
                        {
                            if (_tempnode[_index].node_A._temp > maxtmp) //上下限报警
                                _tempnode[_index].node_A._alarmTmpHigh = true;
                            else
                                _tempnode[_index].node_A._alarmTmpLow = true;
                        }
                        else
                        {
                            _tempnode[_index].node_A._alarmTmpHigh = false;
                            _tempnode[_index].node_A._alarmTmpLow = false;
                        }

                        //湿度
                        _tempnode[_index].node_A._humidity = f_hum;

                        //判断1号或2号是否有报警
                        if (span.checkInSpan(_tempnode[_index].node_A._humidity, minhmd, maxhmd)) //确定湿度报警
                        {
                            if (_tempnode[_index].node_A._humidity > maxhmd) //上下限报警
                                _tempnode[_index].node_A._alarmHmdHigh = true;
                            else
                                _tempnode[_index].node_A._alarmHmdLow = true;
                        }
                        else
                        {
                            _tempnode[_index].node_A._alarmHmdHigh = false;
                            _tempnode[_index].node_A._alarmHmdLow = false;
                        }

                        //更新显示面板的时间
                        _tempnode[_index].node_A._updateTime = otherfuc.GetUnixNow();
                        MainTempBoards[_index].Nodes = _tempnode[_index];
              
                        //温度报警
                        if (_tempnode[_index].node_A._alarmTmpHigh == true || _tempnode[_index].node_A._alarmTmpLow == true)
                        {
                            tmpAlarm = true;
                        }
                        else
                            tmpAlarm = false;

                        //湿度报警
                        if (_tempnode[_index].node_A._alarmHmdHigh == true || _tempnode[_index].node_A._alarmHmdLow == true)
                        {
                            hmdAlarm = true;
                        }
                        else
                            hmdAlarm = false;
                        //温湿度都报警标志
                        if ((tmpAlarm == true) && (hmdAlarm == true))
                            MainTempBoards[_index].IsAlarmFlag = true;
                        else
                            MainTempBoards[_index].IsAlarmFlag = false;
                        //只有温度报警标志
                        if ((tmpAlarm == true) && (hmdAlarm == false))
                            MainTempBoards[_index].IsTmpAlarmFlag = true;
                        else
                            MainTempBoards[_index].IsTmpAlarmFlag = false;
                        //只有湿度报警标志
                        if ((hmdAlarm == true) && (tmpAlarm == false))
                            MainTempBoards[_index].IsHmdAlarmFlag = true;
                        else
                            MainTempBoards[_index].IsHmdAlarmFlag = false;

                        //更新显示面板
                        MainTempBoards[_index].UpdateGraph();
                    }
                }

                #endregion
                
        #endregion

        #region 监控面板编辑

                #region  快捷栏收缩

                /// <summary>
                /// Self_Function:快捷栏收缩
                /// </summary>
                private void shrink()
                {
                    this.toolStrip2.Height = 0;
                    this.ButtonMapMange.Height = 0;
                    this.ButtonSave.Height = 0;
                    this.ButtonCancle.Height = 0;
                    this.ButtonAuto.Height = 0;
                    this.ButtonQuit.Height = 0;
                    this.label4.Visible = false;
                    this.label3.Visible = false;
                }

                #endregion

                #region  快捷栏收缩

                /// <summary>
                /// Self_Function:快捷栏展开 
                /// </summary>
                private void spread()
                {

                    this.toolStrip2.Height = 25;
                    this.ButtonMapMange.Height = 22;
                    this.ButtonSave.Height = 22;
                    this.ButtonCancle.Height = 22;
                    this.ButtonAuto.Height = 22;
                    this.ButtonQuit.Height = 22;
                    this.label3.Visible = true;
                    this.label4.Visible = true;
                }


                #endregion

                #region 地图管理

                /// <summary>
                /// 地图管理
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void ButtonMapMange_MouseClick(object sender, MouseEventArgs e)
                {
                    //弹出模态窗体
                    DialogResult result = MessageBox.Show("是：加载地图, 否：当前地图恢复默认, 取消：退出当前操作", "提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.None, MessageBoxDefaultButton.Button3);
                    //对当前选择做操作
                    if (result == DialogResult.Yes)
                    {
                        #region 加载

                        OpenFileDialog op = new OpenFileDialog();
                        //标题
                        op.Title = "选择背景图片";

                        //文件初始路径
                        op.InitialDirectory = path + "\\img";

                        //当前文件名筛选器
                        op.Filter = "选择背景图片(*.JPG;*.JPEG;*.JPE;*.JEIF)|*.JPG;*.JPEG;*.JPE;*.JEIF";

                        //文件对话框中当前选定筛选器的索引
                        op.FilterIndex = 1;

                        if (op.ShowDialog() == DialogResult.OK)
                        {
                            string filename = op.FileName;
                            //取得复制文件的文件名
                            string sfilename = Path.GetFileName(filename);
                            //存放的目录及名称(保持原有)
                            string spath = path + "\\img\\" + sfilename;
                            //存放图片的路径
                            string fpath = path + "\\img";
                            //分离文件名
                            string[] pathorname = sfilename.Split('.');
                            //重复时名称
                            string filepathname = fpath + "\\" + pathorname[0] + otherfuc.FormatDate("yyMMddHHmmss") + '.' + pathorname[1];
                            //创建文件夹
                            otherfuc.FileNewfile(fpath, false);

                            if (filename != spath)
                            {
                                if (!File.Exists(spath))
                                {
                                    File.Copy(filename, spath);
                                    MessageBox.Show("操作已成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    this.picBackground.Image = Image.FromFile(spath);
                                    Settings.Default.imagePath = spath;
                                    Settings.Default.Save();

                                }
                                else
                                {
                                    File.Copy(filename, filepathname);
                                    MessageBox.Show("操作已成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    this.picBackground.Image = Image.FromFile(filepathname);
                                    Settings.Default.imagePath = filepathname;
                                    Settings.Default.Save();
                                }
                            }
                            else
                            {
                                MessageBox.Show("应用成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                this.picBackground.Image = Image.FromFile(spath);
                                Settings.Default.imagePath = spath;
                                Settings.Default.Save();
                            }
                        }
                        this.label2.Focus();

                        #endregion
                    }
                    if (result == DialogResult.No)
                    {
                        #region 取消

                        DialogResult resl = MessageBox.Show("确定取消当前背景地图", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
                        if (resl == DialogResult.OK)
                        {
                            this.picBackground.Image = null;
                            Settings.Default.imagePath = null;
                            Settings.Default.Save();

                        }

                        #endregion
                    }

                }

                #endregion

                #region 保存编辑

                /// <summary>
                /// 保存编辑（保存当前显示面板在显示区域内的位置信息）
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void ButtonSave_MouseClick(object sender, MouseEventArgs e)
                {
                    if (isBuildConnect != false)
                    {
                        for (int pdi = 0; pdi < MainTempBoards.Count; pdi++)
                        {
                            using (PanelTablesFunc panelchange = new PanelTablesFunc())
                            {
                                panelchange.updatePanel(MainTempBoards[pdi].panelName.ToString(),
                                                        MainTempBoards[pdi].maxTemp.ToString(),
                                                        MainTempBoards[pdi].paneladdr.ToString(),
                                                        MainTempBoards[pdi].panelid,
                                                        MainTempBoards[pdi].Location.X - this.label2.Location.X,
                                                        MainTempBoards[pdi].Location.Y - this.label2.Location.Y);
                            }
                        }
                        MessageBox.Show("应用成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("保存编辑失败<连接未打开>", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    this.panel1.Focus();
                }

                #endregion

                #region 取消编辑

                /// <summary>
                /// 取消编辑(恢复显示面板移动前的状态)
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void ButtonCancle_MouseClick(object sender, MouseEventArgs e)
                {

                    if (isBuildConnect == true)
                    {
                        DialogResult result = MessageBox.Show("确认恢复到保存前的状态吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                        int panelnums = MainTempBoards.Count;
                        if (result == DialogResult.OK && panelnums > 0)
                        {
                            string _value = null;
                            using (PanelTablesFunc db = new PanelTablesFunc())
                            {
                                for (int i = 0; i < panelnums - 1; i++)
                                {
                                    _value += MainTempBoards[i].panelid.ToString() + ",";
                                }
                                _value += MainTempBoards[panelnums - 1].panelid + ",";

                                DataSet ds = new DataSet();
                                ds = db.selcPanel(_value);
                                int _index = 0;
                                for (int i = 0; i < panelnums; i++)
                                {
                                    _index = i;
                                    int d_panelid = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);
                                    int m_panelid = MainTempBoards[i].panelid;
                                    if (d_panelid != m_panelid) // 如果顺序不一样
                                    {
                                        for (int j = 0; j < panelnums; j++)
                                        {
                                            if (m_panelid == Convert.ToInt32(ds.Tables[0].Rows[j].ItemArray[0]))
                                            {
                                                _index = j;
                                                break;
                                            }
                                        }
                                    }
                                    MainTempBoards[i].Location = new Point(Convert.ToInt32(ds.Tables[0].Rows[_index].ItemArray[1]) + label2.Location.X,
                                                                            Convert.ToInt32(ds.Tables[0].Rows[_index].ItemArray[2]) + label2.Location.Y);
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("取消编辑失败<连接未打开>", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    this.panel1.Focus();
                }

                #endregion

                #region 自动排列

                /// <summary>
                /// 自动排列
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void ButtonAuto_MouseClick(object sender, MouseEventArgs e)
                {
                    int swidth = this.panel1.Width;
                    //当前窗体能排列的个数
                    int total = Convert.ToInt32(swidth / 120);

                    if (isBuildConnect == false)
                    {
                        MessageBox.Show("未建立连接", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    for (int pdi = 0; pdi < MainTempBoards.Count; pdi++)
                    {
                        MainTempBoards[pdi].Left = (pdi % total) * 120 + this.label2.Location.X;
                        MainTempBoards[pdi].Top = Convert.ToInt16(pdi / total) * 110 + this.label2.Location.Y + 5;
                    }

                    //置于底层
                    this.picBackground.SendToBack();
                }

                #endregion

                #region 退出编辑

                /// <summary>
                /// 退出编辑
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void ButtonQuit_MouseClick(object sender, MouseEventArgs e)
                {
                    //快捷栏收缩
                    shrink();

                    if (MainTempBoards != null)
                    {
                        for (int i = 0; i < MainTempBoards.Count; i++)
                        {
                            MainTempBoards[i].ControlBoard_AllowDrag(false);
                        }

                    }

                    this.panel1.Focus();
                }


                #endregion
                
        #endregion

        #region F1帮助

        /// <summary>
        /// /// F1帮助
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                if (File.Exists(Dirpath.Syspath + helpname))
                {
                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo.FileName = Dirpath.Syspath + helpname;
                    p.Start();
                }
                else
                {
                    MessageBox.Show("未找到帮助文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void label2_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            panel1_PreviewKeyDown(sender, e);
        }

        private void toolStrip2_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            panel1_PreviewKeyDown(sender, e);
        }

        #endregion

        #region 窗体关闭退出到托盘

        /// <summary>
        /// 双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.Visible == false)
                {
                    this.Visible = true;
                    this.Activate();
                }
                else
                    this.Visible = false;
            }
        }
        /// <summary>
        /// 重写点击最小化的事件，使其保持现有的状态，隐藏窗体
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            int WM_SYSCOMMAND = 0x112;
            int SC_MINIZE = 0xF020;
            int SC_CLOSE = 0xF060;
            if (m.Msg == WM_SYSCOMMAND)//收到的是点击标题栏上的内容时产生的
            {
                if (m.WParam.ToInt32() == SC_MINIZE || m.WParam.ToInt32() == SC_CLOSE)//此消息是点击最小化按钮或关闭按钮产生的
                {
                    this.Visible = false;
                    return;
                }
            }
            base.WndProc(ref m);
        }

        /// <summary>
        /// 托盘右键，打开软件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openSoft_Click(object sender, EventArgs e)
        {
            if (this.Visible == false)
            {
                this.Visible = true;
                this.Activate();
            }
        }

        /// <summary>
        /// 托盘右键，关闭软件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CloseSoft_Click(object sender, EventArgs e)
        {
            系统退出ToolStripMenuItem1_Click(sender, e);
        }

        #endregion     

        #region 浮点数验证

        /// <summary>
        /// 浮点数验证
        /// </summary>
        /// <param name="fnum">待验证的数据</param>
        /// <returns>是否匹配</returns>
        private bool IsFloat(string fnum)
        {
            Regex rx = new Regex(@"^\-{0,1}\d{1,3}(\.\d{1,2}){0,1}$");
            return rx.IsMatch(fnum);
        }

        #endregion

    }
}